#include "stdafx.h"
#include "cvxDeckLinkInput.h"
#include <stdio.h>
#include <comutil.h>
#include <assert.h>



CvxDeckLinkInput::CvxDeckLinkInput()
{
	m_pdeckLink = NULL;
	m_pinputCard = NULL;

	// Create an IDeckLinkIterator object to enumerate all DeckLink cards in the system
	IDeckLinkIterator *pIterator = NULL;
	HRESULT result = CoCreateInstance(CLSID_CDeckLinkIterator, NULL, CLSCTX_ALL, IID_IDeckLinkIterator, 
									  (void**)&pIterator);
	if (FAILED(result) || pIterator == NULL)
	{
		AfxMessageBox(_T("A DeckLink iterator could not be created."), MB_OK);
		return;
	}

	//only support one capture card in current system
	if (pIterator->Next(&m_pdeckLink) == S_FALSE)
	{
		pIterator->Release();
		AfxMessageBox(_T("A DeckLink Card can not be found"), MB_OK);
		return;
	}
	pIterator->Release();	
	//query input card
	result = m_pdeckLink->QueryInterface(IID_IDeckLinkInput, (void**)&m_pinputCard);
	if (result != S_OK)
	{
		AfxMessageBox(_T("query decklink input failed."), MB_OK);
		return ;
	}
}


CvxDeckLinkInput::~CvxDeckLinkInput()
{
	if (m_pdeckLink)
	{
		m_pdeckLink->Release();
	}
	if (m_pinputCard)
	{
		m_pinputCard->Release();
	}
	
	CoUninitialize();
}

CString CvxDeckLinkInput::GetModeName(void)
{
	BSTR deviceNameBSTR = NULL;		
	HRESULT result = m_pdeckLink->GetModelName(&deviceNameBSTR); 
	if (result == S_OK) 
	{
		return CString(deviceNameBSTR);	
	}
	else
	{
		return CString("No DeckLink Cards Found.");
	}

}

HRESULT CvxDeckLinkInput::SetFormat(BMDDisplayMode displayMode,	BMDPixelFormat pixelFormat, int flag)
{
	HRESULT	rst = m_pinputCard->StopStreams();
	if (rst != S_OK)
	{	
		TRACE("Input StopStreams failed with result %08x\n", rst);
		return rst;
	}
	rst = m_pinputCard->EnableVideoInput(displayMode, pixelFormat, flag);
	if (rst != S_OK)
	{	
		TRACE("Input EnableVideoInput failed with result %08x\n", rst);
		return rst;
	}
	rst = m_pinputCard->StartStreams();
	if (rst != S_OK)
	{	
		TRACE("Input EnableVideoInput failed with result %08x\n", rst);
		return rst;
	}
	return rst;
}
HRESULT CvxDeckLinkInput::StartStream(BMDDisplayMode displayMode, BMDPixelFormat pixelFormat, int flag )
{
	HRESULT rst = m_pinputCard->EnableVideoInput(displayMode, pixelFormat, flag);
//	assert(rst == S_OK);
	rst = m_pinputCard->StartStreams();
//	assert(rst == S_OK);
	return S_OK;
}
void CvxDeckLinkInput::StopStream(void)
{
	m_pinputCard->StopStreams();
	m_pinputCard->DisableVideoInput();
}
int CvxDeckLinkInput::AvailableCount(void)
{
	unsigned long availableFrameCount;
	HRESULT rst = m_pinputCard->GetAvailableVideoFrameCount(&availableFrameCount);
	assert(rst == S_OK);
	return availableFrameCount;
}

HRESULT CvxDeckLinkInput::SetCallback(IDeckLinkInputCallback *pCallback)
{
	return m_pinputCard->SetCallback(pCallback);
}

